<?php
/**
 * Created by PhpStorm.
 * User: mr.lee
 * Date: 2018-12-18
 * Time: 22:33
 */

namespace app\common\controller;


use app\common\model\Agent;
use app\common\model\EfapiaoGoods;
use app\common\model\EfapiaoList;
use app\common\model\Merchant;
use app\common\model\Paylog;
use app\common\model\WxOpen;
use Ekaipiao\Epiao;
use think\Controller;
use Wechat\Wxobjopen;

class Ekaipiao extends Controller
{
    public function save_fp($sinfo)
    {
        $Paylog = new Paylog();
        $payinfo = $Paylog->where('orderid', $sinfo['SuccOrderId'])->field('mid,price')->find();
        $data = array(
            's_pappid' => $sinfo['SPAppId'],
            'order_id' => $sinfo['SuccOrderId'],

        );
        $map['id'] = $payinfo['mid'];
        $Merchant = new Merchant();
        $Agent = new Agent();
        $WxOpen = new WxOpen();
        $user = $Merchant->where($map)->find();
        $config = $Agent->where(array('id' => $user['agent']))->find();
//        $users = $WxOpen->where(array('id' => $config['wx_open_id']))->find();
        $usersopen = $WxOpen->where(array('id' => $user['wx_open_id']))->find();
        $options = array(
            'component_token' => $config['component_token'], // 填写你设定的key
            'component_encodingaeskey' => $config['component_encodingaeskey'], // 填写加密用的EncodingAESKey
            'component_appid' => $config['component_appid'], // 填写高级调用功能的app id
            'component_appsecret' => $config['component_appsecret'], // 填写高级调用功能的密钥
            'open_ticket' => $config['open_ticket'],
            'authorizer_appid' => $usersopen['authorizer_appid'],
            'authorizer_refresh_token' => $usersopen['authorizer_refresh_token'],
        );
        $weObj = new Wxobjopen($options);

        $authdata = $weObj->getauthdata($data);

//        return $authdata;
        if ($authdata['errcode'] == 0) {
            $user_auth_info = $authdata['user_auth_info'];
//           $phone= isset($user_auth_info['biz_field']['phone']) ? $user_auth_info['biz_field']['phone'] : "";
//           return $phone;
            if (isset($user_auth_info['user_field'])) {
                $efp_data['gfmc'] = isset($user_auth_info['user_field']['title']) ? $user_auth_info['user_field']['title'] : "";
                $efp_data['dzdh'] = isset($user_auth_info['user_field']['phone']) ? $user_auth_info['user_field']['phone'] : "";
                $efp_data['email'] = isset($user_auth_info['user_field']['email']) ? $user_auth_info['user_field']['email'] : "";
            } elseif (isset($user_auth_info['biz_field'])) {
                $efp_data['gfmc'] = isset($user_auth_info['biz_field']['title']) ? $user_auth_info['biz_field']['title'] : "";
                $addr = isset($user_auth_info['biz_field']['addr']) ? $user_auth_info['biz_field']['addr'] : "";
                $phone = isset($user_auth_info['biz_field']['phone']) ? $user_auth_info['biz_field']['phone'] : "";
                $efp_data['dzdh'] = $addr . " " . $phone;
                $efp_data['email'] = isset($user_auth_info['biz_field']['email']) ? $user_auth_info['biz_field']['email'] : "";
                $bank_type = isset($user_auth_info['biz_field']['bank_type']) ? $user_auth_info['biz_field']['bank_type'] : "";
                $bank_no = isset($user_auth_info['biz_field']['bank_no']) ? $user_auth_info['biz_field']['bank_no'] : "";
                $efp_data['yhzh'] = $bank_type . " " . $bank_no;
                $efp_data['sh'] = isset($user_auth_info['biz_field']['tax_no']) ? $user_auth_info['biz_field']['tax_no'] : "";
            }
            $efp_data['fpzl'] = "t";
            $efp_data['bz'] = $sinfo['SuccOrderId'];
            $efp_data['mid'] = $payinfo['mid'];
            $efp_data['orderid'] = $sinfo['SuccOrderId'];
            $efp_data['openid'] = $sinfo['FromUserName'];
            $efp_data['appid'] = $usersopen['authorizer_appid'];
            $efp_data['invoice'] = $user['efp_invoice'];
            $efp_data['kpjh'] = $user['efp_kpjh'];
            $efp_data['create_time'] = time();
            $goodsinfo = json_encode($this->goodsinfo($payinfo), JSON_UNESCAPED_UNICODE);
            $efp_data['goodsinfo'] = json_encode($this->goodsinfo($payinfo), JSON_UNESCAPED_UNICODE);
            $EfapiaoList = new EfapiaoList();
            $info = $EfapiaoList->where('orderid', $sinfo['SuccOrderId'])->find();
            if (!$info) {
                $EfapiaoList->save($efp_data);
            }
            if ($user['efp_isauto'] == "Y") {
                if (!empty($goodsinfo)) {
                    $kp = $this->send_kp($sinfo['SuccOrderId']);
                }
            }
            return $kp;


        }
    }

    private function goodsinfo($payinfo)
    {
        $EfapiaoGoods = new EfapiaoGoods();
        $emap['mid'] = $payinfo['mid'];
        $emap['is_default'] = "Y";
        $default_goods = $EfapiaoGoods->where($emap)->limit(1)->select();
        $fpmm_info = "";
        foreach ($default_goods as $k => $v) {
            $fpmm_info['group' . $k]['spmc'] = $v['spmc'];//商品名称
            $fpmm_info['group' . $k]['ggxh'] = $v['ggxh'];//规格型号
            $fpmm_info['group' . $k]['jldw'] = $v['jldw'];//计量单位
            $fpmm_info['group' . $k]['spsl'] = $v['spsl'];//商品数量
            $fpmm_info['group' . $k]['spdj'] = $payinfo['price'];//$v['spdj'];//商品单价
            $fpmm_info['group' . $k]['je'] = $payinfo['price'];//$v['je'];//金额
            $fpmm_info['group' . $k]['slv'] = $v['slv'];//税率
            $fpmm_info['group' . $k]['se'] = number_format(($payinfo['price'] * $v['slv']),2,".","");//$v['se'];//税额
            $fpmm_info['group' . $k]['hsbz'] = $v['hsbz'];//含税标志
            $fpmm_info['group' . $k]['spbm'] = $v['spbm'];//含税标志
            $fpmm_info['group' . $k]['SYYHZCBZ'] = $v['syyhzcbz'];
            $fpmm_info['group' . $k]['YHZCSM'] = $v['yhzcsm'];
        }
        return $fpmm_info;
    }

    public function send_kp($orderid)
    {
        $EfapiaoList = new EfapiaoList();
        $epiaoinfo = $EfapiaoList->where('orderid', $orderid)->find();

        $fpmm_info = json_decode($epiaoinfo['goodsinfo'], true);
        $kpxx_arr = array(
            'gfmc' => $epiaoinfo['gfmc'],//购方名称
            'sh' => $epiaoinfo['sh'],//税号
            'yhzh' => $epiaoinfo['yhzh'],//银行账号
            'dzdh' => $epiaoinfo['dzdh'],//地址电话
            'email' => $epiaoinfo['email'],//邮箱
            'fpzl' => $epiaoinfo['fpzl'],//发票种类s专票 c普票 t 电子发票
            'bz' => $epiaoinfo['bz'],//备注
        );

        $doc = new \DOMDocument('1.0', 'utf-8');
        $doc->formatOutput = true;//格式化输出格式
        $business = $doc->createElement('business');//创建一个标签
        $body = $doc->createElement('body');//创建一个标签
        $input = $doc->createElement('input');//创建一个标签
        $kpxx = $doc->createElement('kpxx');//创建一个标签
        $fpmx = $doc->createElement('fpmx');//创建一个标签
        //开票信息内容
        foreach ($kpxx_arr as $k => $v) {
            $a[$k] = $doc->createElement($k);
            $a[$k]->appendChild($doc->createTextNode($v));
            $kpxx->appendChild($a[$k]);
            $input->appendChild($kpxx);
        }
        $fpmx_info = $doc->createTextNode(count($fpmm_info));//设置属性内容
        $fpmx_id = $doc->createAttribute('count');//设置属性
        $fpmx_id->appendChild($fpmx_info);//将属性内容赋给属性
        $fpmx->appendChild($fpmx_id);
        $i = 1;
        foreach ($fpmm_info as $ks => $vs) {
            $group[$ks] = $doc->createElement('group');
            foreach ($vs as $ka => $va) {

                $group_info[$ks] = $doc->createTextNode($i);//设置属性内容
                $group_id[$ks] = $doc->createAttribute('xh');//设置属性
                $group_id[$ks]->appendChild($group_info[$ks]);//将属性内容赋给属性
                $group[$ks]->appendChild($group_id[$ks]);

                $b[$ka] = $doc->createElement($ka);
                $b[$ka]->appendChild($doc->createTextNode($va));
                $group[$ks]->appendChild($b[$ka]);
                $fpmx->appendChild($group[$ks]);

            }
            $i++;

            $input->appendChild($fpmx);

        }
        //开票信息内容结束

        $business_info = $doc->createTextNode("zzsfp");//设置属性内容
        $business_id = $doc->createAttribute('id');//设置属性
        $business_id->appendChild($business_info);//将属性内容赋给属性
        $business_info2 = $doc->createTextNode($orderid);//设置属性内容
        $business_id2 = $doc->createAttribute('comment');//设置属性
        $business_id2->appendChild($business_info2);//将属性内容赋给属性（订单号）
        $input->appendChild($kpxx);
        $body_info = $doc->createTextNode("1");//设置属性内容
        $body_id = $doc->createAttribute('yylxdm');//设置属性
        $body_id->appendChild($body_info);//将属性内容赋给属性
        $body->appendChild($body_id);
        $body->appendChild($input);

        $business->appendChild($business_id);//将属性赋给标签
        $business->appendChild($business_id2);//将属性赋给标签
        $business->appendChild($body);


        $doc->appendChild($business);
        $xml = $doc->saveXML();
//return $xml;
        $Epiao = new Epiao();
        $data = array(
            'invoice' => $epiaoinfo['invoice'],
            'kpjh' => $epiaoinfo['kpjh'],
            'token' => $Epiao->token($epiaoinfo['mid']),
            'xml' => $xml,
            'appid' => $epiaoinfo['appid'],
            'orderId' => $epiaoinfo['orderid'],
            'os_type' => "Linux",

        );
        $Epiao = new Epiao();
        $at = $Epiao->kaipiao($data);
        if ($at['errcode'] == "200") {
            $EfapiaoList->save(['status' => 9], ['orderid' => $orderid]);
            $re_param['result_code'] = "SUCCESS";
            $re_param['result_msg'] = "开票成功";
            $Paylog=new Paylog();
            $Paylog->save(['is_efp_receipt'=>"Y"],['orderid'=>$orderid]);
        } else {
            $re_param['result_code'] = "FAIL";
            $re_param['result_msg'] = "开票失败" . $at['errcode'] . $at['errmsg'];
        }
        return $re_param;
    }

}